package com.nhc.activity_fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.astrob.model.LonLat;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.nhc.database.dbmodel.TrackPoint;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.model.TripItem;
import com.nhc.view.TripItemViewLayout;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.formatter.SimpleAxisValueFormatter;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import zuo.biao.library.base.BaseFragment;

public class NaviTrackChatFragment extends BaseFragment {
    private final String TAG = "NaviTrackChatFragment";

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static NaviTrackChatFragment createInstance() {
        return new NaviTrackChatFragment();
    }
    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    private WayTrail wayTrailEdit = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.navitrackchat_fragment);
        wayTrailEdit = DBDataCenter.getInstance().wayTrailEdit;

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private TripItemViewLayout navitrackinfo_0;
    private TripItemViewLayout navitrackinfo_1;
    private LineChartView ll_chart_1;

    @Override
    public void initView() {//必须在onCreateView方法内调用
        navitrackinfo_0 = (TripItemViewLayout) findViewById(R.id.navitrackinfo_0);
        navitrackinfo_1 = (TripItemViewLayout) findViewById(R.id.navitrackinfo_1);

        ll_chart_1 = (LineChartView) findViewById(R.id.ll_chart_1);
        ll_chart_1.setVisibility(View.GONE);

    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    public boolean _isWorking = false;

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initData() {//必须在onCreateView方法内调用
        if (_isWorking) {
            return;
        }
        _isWorking = true;
        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                setData();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        _isWorking = false;
                        String UP[] = SysUtils.getInstance().getDistanceStr((int) wayTrailEdit.getTrail_distance());
                        navitrackinfo_0.bindView(new TripItem(getString(R.string.zjl), UP[0], UP[1]));
                        String MAX[] = SysUtils.getInstance().getDistanceStr(wayTrailEdit.getMaxalt());
                        navitrackinfo_1.bindView(new TripItem(getString(R.string.hb), MAX[0], MAX[1]));
                        if (wayTrailEdit.trackPointList.size() > 1) {
                            initLineChart();
                        }
                        dismissProgressDialog();
                    }
                });
            }
        });
    }

    private void refreshData(TrackPoint tp, PointValue value) {
        if (tp == null || value == null) {
//            navitrackinfo_0.bindView(new TripItem("距离", "", ""));
            navitrackinfo_1.bindView(new TripItem(getString(R.string.hb), "", ""));
            return;
        }
        String ALT[] = SysUtils.getInstance().getDistanceStr((int) tp.getAltitude());
        navitrackinfo_1.bindView(new TripItem(getString(R.string.hb), ALT[0], ALT[1]));

        String VEL[] = SysUtils.getInstance().getVelStr(tp.getSpeed());
        navitrackinfo_0.bindView(new TripItem(getString(R.string.vel), VEL[0], VEL[1]));
    }

    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
    private List<PointValue> mPoint2Values = new ArrayList<PointValue>();

    private List<AxisValue> mAxisY2Values = new ArrayList<AxisValue>();

    private List<Integer> mTPIndex = new ArrayList<Integer>();

    double _scale = 1;
    double _sub = 0;
    double _scale2 = 1;
    double _sub2 = 0;

//    x距离-y高度
//    x时间-y距离

    public String getTimeStr(long datetime) {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "M-dd HH:mm");
        Date curDate = new Date(datetime);
        String res = formatter.format(curDate);
        return res;
    }

    private void setData() {
        if (wayTrailEdit.trackPointList == null) {
            return;
        }

        mTPIndex.clear();
        int size = wayTrailEdit.trackPointList.size();
        if (size < 1) {
            return;
        }

        int velMax = 10;
        for (int i = 1; i < size; i++) {
            TrackPoint tp = wayTrailEdit.trackPointList.get(i);
            if (velMax < tp.getSpeed() * 3.6f) {
                velMax = (int) (tp.getSpeed() * 3.6f);
            }
        }

        if (velMax < 10) {
            velMax = 10;
        } else {
            velMax = (velMax / 10 + 1) * 10;
        }

        _scale2 = 200.0 / velMax;
        _sub2 = 0;

        //两个y轴都和0～200的Y轴 对比
        _scale = 200.0 / (wayTrailEdit.getMaxalt() - wayTrailEdit.getMinalt());//假设幅度是1000～2000
        _sub = wayTrailEdit.getMinalt();

        double distance = 0;
        LonLat llA = wayTrailEdit.trackPointList.get(0).getLL();

        int step = size/1000;//最多1000个点
        if (step < 1) {
            step = 1;
        }
        for (int i = 1; i < size; i++) {
            TrackPoint tp = wayTrailEdit.trackPointList.get(i);
            LonLat llB = tp.getLL();
            distance += Start.getInstance().MapKit().getDistance(llA, llB);
            llA = llB;

            if (i % step == 0) {
                //设置X 轴的显示
                double x = distance;
                //图表的每个点的显示
                double alt = tp.getAltitude();
                alt = (alt - _sub) * _scale;
                mPointValues.add(new PointValue((float) x, (float) alt));
                double vel = tp.getSpeed() * 3.6f;
                vel = vel * _scale2 + _sub2;
                mPoint2Values.add(new PointValue((float) x, (float) vel));
            }

        }

        //
        //distance 米
        int dd = (int) (distance/1000);
        if (dd < 100) {
            dd = 100;
        }

        for (int j = 1; j < distance / dd; j++) {
            String xName = new DecimalFormat("0.0").format(j * dd / 1000.0) + "km";
            mAxisXValues.add(new AxisValue(j * dd).setLabel(xName));
            mTPIndex.add(j);
        }

    }

    //图表参数说明
    //http://blog.csdn.net/u013360656/article/details/52875230
//    http://www.jianshu.com/p/90a544b739b1
//    https://github.com/lecho/hellocharts-android/blob/master/hellocharts-samples/src/lecho/lib/hellocharts/samples/TempoChartActivity.java
    private void initLineChart() {
        ll_chart_1.setVisibility(View.VISIBLE);
        List<Line> lines = new ArrayList<Line>();
        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(true);//曲线是否平滑，即是曲线还是折线
        line.setFilled(true);//是否填充曲线的面积
        line.setHasLabels(false);//曲线的数据坐标是否加上备注
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        lines.add(line);

        Line line2 = new Line(mPoint2Values).setColor(Color.parseColor("#8ADA53"));//绿色
        line2.setShape(ValueShape.DIAMOND);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line2.setCubic(true);//曲线是否平滑，即是曲线还是折线
        line2.setFilled(true);//是否填充曲线的面积
        line2.setHasLabels(false);//曲线的数据坐标是否加上备注
        line2.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line2.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        lines.add(line2);

        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.GRAY);  //设置字体颜色
        axisX.setName(getString(R.string.sjjihb));  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(6); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        axisX.setHasLines(true); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setName(getString(R.string.jlhb));//y轴标注
        axisY.setTextSize(10);//设置字体大小
        axisY.setTextColor(Color.parseColor("#FFCD41"));
        axisY.setFormatter(new Axis1ValueFormatter(_scale, _sub, 0));
        data.setAxisYLeft(axisY);  //Y轴设置在左边


        Axis axisY2 = new Axis();  //Y轴
        axisY2.setName(getString(R.string.vel) + "(km/h)");//y轴标注
        axisY2.setTextSize(10);//设置字体大小
        axisY2.setTextColor(Color.parseColor("#8ADA53"));
        axisY2.setFormatter(new Axis2ValueFormatter(_scale2, _sub2, 0));
        axisY2.setHasLines(true);
        data.setAxisYRight(axisY2);  //y轴设置在右边

        int size = mTPIndex.size();
        int maxZoom = 20;
        maxZoom = size / 3;
        if (maxZoom < 2) {
            maxZoom = 2;
        }

        //设置行为属性，支持缩放、滑动以及平移
        ll_chart_1.setInteractive(true);
        ll_chart_1.setZoomType(ZoomType.HORIZONTAL);
        ll_chart_1.setMaxZoom((float) maxZoom);//最大方法比例
        ll_chart_1.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        ll_chart_1.setLineChartData(data);
        ll_chart_1.setVisibility(View.VISIBLE);
        ll_chart_1.setOnValueTouchListener(new LineChartOnValueSelectListener() {

            @Override
            public void onValueDeselected() {
            }

            @Override
            public void onValueSelected(int lineIndex, int pointIndex, PointValue value) {
                if (pointIndex >= 0 && pointIndex < mTPIndex.size()) {
                    int index = mTPIndex.get(pointIndex);
                    refreshData(wayTrailEdit.trackPointList.get(index), value);
                }
            }
        });
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
//        这4句代码可以设置X轴数据的显示个数（x轴0-7个数据）。
//        1 当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。
//        2 当数据点个数大于（29）的时候。
//        2.1 若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
//        2.2 若设置axisX.setMaxLabelChars(int count)这句话,33个数据点测试，
//        2.2.1 若 axisX.setMaxLabelChars(10); 里面的10大于v.right= 7; 里面的7，则 刚开始X轴显示7条数据，然后缩放的时候X轴的个数会保证大于7小于10
//        2.2.2 若小于v.right= 7;中的7,反正我感觉是这两句都好像失效了的样子 - -! 若这儿不设置 v.right= 7; 这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差

        //初始显示0～4的数据
//        Viewport v = new Viewport(ll_chart_1.getMaximumViewport());
//        v.left = 0;
//        v.right = 4;
//        ll_chart_1.setCurrentViewport(v);

        Viewport v = new Viewport(ll_chart_1.getMaximumViewport());
        ll_chart_1.setMaximumViewport(v);//最大窗口

//        Viewport v1 = ll_chart_1.getMaximumViewport();
//        v1.set(v.left, tempoRange, v1.right, 0);
//        ll_chart_1.setMaximumViewport(v);
//        ll_chart_1.setCurrentViewport(v);
    }

    private static class Axis1ValueFormatter extends SimpleAxisValueFormatter {

        private double scale;
        private double sub;
        private int decimalDigits;

        public Axis1ValueFormatter(double scale, double sub, int decimalDigits) {
            this.scale = scale;
            this.sub = sub;
            this.decimalDigits = decimalDigits;
        }

        @Override
        public int formatValueForAutoGeneratedAxis(char[] formattedValue, float value, int autoDecimalDigits) {
            double scaledValue = value / scale + sub;
            return super.formatValueForAutoGeneratedAxis(formattedValue, (float) scaledValue, this.decimalDigits);
        }
    }

    private static class Axis2ValueFormatter extends SimpleAxisValueFormatter {

        private double scale;
        private double sub;
        private int decimalDigits;

        public Axis2ValueFormatter(double scale, double sub, int decimalDigits) {
            this.scale = scale;
            this.sub = sub;
            this.decimalDigits = decimalDigits;
        }

        @Override
        public int formatValueForAutoGeneratedAxis(char[] formattedValue, float value, int autoDecimalDigits) {
            double scaledValue = (value - sub) / scale;
            return super.formatValueForAutoGeneratedAxis(formattedValue, (float) scaledValue, this.decimalDigits);
        }
    }
    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用

    }
    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


}